import React, { Component, PropTypes } from 'react';
import {
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  Image,
  Dimensions,
  Platform
} from 'react-native';

import _ from 'lodash';
import styles from '../order/orderListStyle';
import CustomListView from '../global/CustomListView';
import ToastTip from '../global/ToastTip';
import ListViewActivityIndicator from '../global/ListViewActivityIndicator';

import OrderCard from '../order/orderCard';
import api from '../../services/api';
const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');

class OrderFinishedList extends Component {
    constructor(props) {
		super(props);

		this.state = {
			currentPage: 1,
            noData: false,
            pagesize: 10,
		};

		this._onRefresh = this._onRefresh.bind(this);
		this._onLoadMore = this._onLoadMore.bind(this);
		this._viewOrder = this._viewOrder.bind(this);
        this.list = [];
        this.totalpage = 0;
        this.currentPage = 1;
		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    componentDidMount() {
        this._mounted = true;
        this.onLoad();
	}

    _onNavigatorEvent(event){
        // console.log("$$$", event);

        // if (event.type === 'ScreenChangedEvent') {
		// 	if (event.id === 'didAppear') { //出现时
        //         this.onLoad();
		// 	}
		// }
    }

    componentWillUnmount(){
        this._mounted = false;
        this.timeIndex && clearTimeout(this.timeIndex);
    }

    onLoad(){
        //加载数据
        if(this.state.noData){
            this.setState({ noData: false});
        }

        this._orderList._pullToRefreshListView.beginRefresh(true);
    }

    async _retrieveOrderList() {
        let {service_type} = this.props;

        let list = await api.post('/order/finishlist',{
                      page: 1,
                      pagesize: this.state.pagesize,
                      service_type
                   });

       if(list.cd == 1){
           this.refs.toast.show(list.msg);
           this._orderList._pullToRefreshListView.endRefresh(false);
           return;
       }

       this.currentPage = 1;

       // not pay
       if(Platform.OS == 'ios') {
           this._endOrderList(list.data);
       } else {
           this.timeIndex = setTimeout(() => {
               this._endOrderList(list.data);
           }, 200);
       }

    }

    _endOrderList(list){
        // let no_pay_list = _.filter(list.res, function(o) { return o.status == 1; });
        this.totalpage = list.total_page;
        this.list = list.res;
        if(!this._mounted){
            return;
        }

        if(this.list.length==0){
            this.setState({noData: true});
            return;
        }

        this._orderList.setState({
            dataList: list.res,
            dataSource: this._orderList._dataSource.cloneWithRows(list.res)
        });

        this._activityIndicator.setState({ visible: false,});
        this._orderList._pullToRefreshListView.endRefresh(false);
    }

    async _retrieveNextPage(status) {
// <<<<<<< HEAD
		if (this.currentPage !== this.totalpage) {

			let page;
            page = this.currentPage + 1;
            // this.setState({ currentPage: page });
            this.currentPage = page;

            let {service_type} = this.props;

            let list = await api.post('/order/finishlist',{
                          page: this.currentPage,
                          pagesize: this.state.pagesize,
                          service_type
                       });

           if(list.cd == 1){
               this.refs.toast.show(list.msg);
               this._orderList._pullToRefreshListView.endRefresh(false);
               return;
           }

           const newData = list.data.res;
           newData.map((item, index) => this.list.push(item));

           this._orderList.setState({
               dataList: this.list,
               dataSource: this._orderList._dataSource.cloneWithRows(this.list),
           });
           this._orderList._pullToRefreshListView.endLoadMore(false);

        }else{
            this._orderList._pullToRefreshListView.endLoadMore(true);
        }
// =======
//   		if (this.state.currentPage !== this.totalpage) {

//   			 let page = this.state.currentPage + 1;
//           this.setState({ currentPage: page });

//           let {service_type} = this.props;

//           let list = await api.post('/order/finishlist',{
//                         page: this.state.currentPage,
//                         pagesize: this.state.pagesize,
//                         service_type
//                      });
//           console.log('result',list);
//          if(list.cd == 1){
//              this.refs.toast.show(list.msg);
//              this._orderList._pullToRefreshListView.endRefresh(false);
//              return;
//          }

//          const newData = list.data.res;
//          newData.map((item, index) => this.list.push(item));

//          this._orderList.setState({
//              dataList: this.list,
//              dataSource: this._orderList._dataSource.cloneWithRows(this.list),
//          });
//          this._orderList._pullToRefreshListView.endLoadMore(false);

//       }else{
//           this._orderList._pullToRefreshListView.endLoadMore(true);
//       }
// >>>>>>> master-temp
	}

    _viewOrder(orderId, cardObj) {
        let {navigator} = this.props;
        // dispatch(actions.order.order_get_cardobj(cardObj));

		navigator.push({
            title: "订单详情",
            backButtonTitle:'',
			screen: 'housekeeperapp.orderdetail',
			passProps: {
				orderId
			},
            navigatorStyle:{
                tabBarHidden: true,
                navBarTextColor: 'white',
            	navBarButtonColor: 'white',
            	navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled:false
            },
			// backButtonHidden: true,
			navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("../../../img/hk_back_icon.png")
                    }
                ],
				rightButtons: [
					{
						id: 'reload',
                        testID: 'order_reload',
						title: '刷新'
					}
				]
			}
		});
	}

    _onRefresh() {
        this._retrieveOrderList();
	}

    _onLoadMore(){
        this._retrieveNextPage(this.props.status);
    }

    _renderRow(rowData, sectionID, rowID){
        return (
            <OrderCard info={rowData} topParent={this.props.parent} parent={this} viewOrder={this._viewOrder} navigator={this.props.navigator} />
        )
    }

    _renderNodata(){
        return (
            <View style={styles.noDataContent}>
                <Image source={require('../../../img/hk_no_data.png')} style={styles.leftImage}/>
                <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10}}>暂无任务</Text>
                {this.state.status != 0?null:this._renderBtn()}
            </View>
        );
    }

    render() {
        return (
            this.state.noData?this._renderNodata():
            <View style={styles.finishContainer}>
                <CustomListView
                    contentStyle={{backgroundColor:"#f3f3f3",paddingRight: 13, paddingBottom:10}}
                    ref={(component) => this._orderList = component }
                    onRefresh={this._onRefresh}
                    onLoadMore={this._onLoadMore}
                    renderRow ={this._renderRow.bind(this)}
                    isRemoveSubViews = {"false"}
                />
                <ListViewActivityIndicator
                    ref={ (component) => this._activityIndicator = component }
                    style={{marginRight: 10, position:'absolute', left: (deviceWidth - 20) / 2, top: (deviceHeight - 64 - 40) / 2, }}
                    color={'#a9a9a9'}
                />
                <ToastTip ref="toast" offsetY={160}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
OrderFinishedList = connectHelper(state => state)(OrderFinishedList);

module.exports = OrderFinishedList;
